﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySoft.Data;

namespace Caifu.Pres.Datas
{
	public class PreNetValueThirdData
	{
		/// <summary>
		/// 
		/// </summary>
		public static readonly PreNetValueThirdData Instance = new PreNetValueThirdData();

		private readonly DbSession dbSession = new DbSession("Caifu.Pres");

		public void Save(IList<PreNetValueThird> list)
		{
			foreach (var item in list)
			{
				this.Save(item);
			}
		}

		public void Save(PreNetValueThird item)
		{
			var oldItem = this.Get(item.FundCode, item.ReportDate, item.Source);
			if (oldItem == null)
			{
				this.Add(item);
			}
			else
			{
				if (oldItem.UnitNetValue != item.UnitNetValue
					|| oldItem.AccumulatedNetValue != item.AccumulatedNetValue)
				{
					oldItem.UnitNetValue = item.UnitNetValue;
					oldItem.AccumulatedNetValue = item.AccumulatedNetValue;
					this.Update(oldItem);
				}
			}
		}

		public void Add(PreNetValueThird item)
		{
			item.Detach();
			item.Id = Guid.NewGuid();
			item.AddTime = DateTime.Now;
			item.UpdateTime = DateTime.Now;

			dbSession.Save(item);
		}

		public void Update(PreNetValueThird item)
		{
			item.Attach();
			item.UpdateTime = DateTime.Now;

			dbSession.Save(item);
		}

		public PreNetValueThird Get(string fundCode, DateTime reportDate, string source)
		{
			var where = PreNetValueThird._.FundCode == fundCode && PreNetValueThird._.ReportDate == reportDate && PreNetValueThird._.Source == source;
			return dbSession.From<PreNetValueThird>()
				.Where(where)
				.ToSingle();
		}

		public IList<PreNetValueThird> List(DateTime reportDate)
		{
			var where = PreNetValueThird._.ReportDate == reportDate;
			return dbSession.From<PreNetValueThird>()
				.Where(where)
				.ToList();
		}

		public IList<PreNetValueThird> List(DateTime reportDate, string source)
		{
			var where = PreNetValueThird._.ReportDate == reportDate && PreNetValueThird._.Source == source;
			return dbSession.From<PreNetValueThird>()
				.Where(where)
				.ToList();
		}
	}
}
